/** 
 * @include "./lib/core.js"
 */

/** @type {Boolean} */
var user_clicked_type = false;


$(document).ready( function() {

//		$( '.select-current' ).customSelect();
	//FIXME
//		$( '.cselect' ).customSelect();
		
		new Image().src = 'static/images/siteProof/ajax-loader.gif';

		// Placeholder
//		$('.js-placeholder').placeholder();
		
//		if($('.signin').length) {
//			$('.login input, .pass input').placeholder();
//		}
		if($('.company-search').length) {
			$('.company-search').placeholder();
		}
		if($('.login-fields').length) {
			$('.login-fields, .pass-fields').placeholder();
		}

		$('#user-location-navigate-field').placeholder();


//		$('#linkNearWomans').bind('click',function(){
//			nearSex = 0;
//			loadWhoIsNear($('#distance-value').html());
//			$('#linkNearMens').attr('class','link-male');
//			$(this).attr('class','link-female link-female-current');
//			return false;
//		});
//
//		$('#linkNearMens').bind('click',function(){
//			nearSex = 1;
//			loadWhoIsNear($('#distance-value').html());
//			$('#linkNearWomans').attr('class','link-female');
//			$(this).attr('class','link-male link-male-current');
//			return false;
//		});

		// Who's near
//		if ($('#near-slider').length){
//			$('#near-slider').slider({
//				min   : 0,
//				max   : 100,
//				range : 'min',
//				change : function(event, ui){
//					$('#distance-value').html(ui.value);
//					loadWhoIsNear(ui.value);
//				}
//
//			});
//		}

		// Lang - для новой верстки
//		$('a.lang-current-container').click(function(e) {
//			e.stopPropagation();
//			var $lang = $('.lang-list');
//			if($lang.css('display') == 'none') {
//				$lang.show();
//			} else {
//				$lang.hide();
//			}
//			return false;
//		});
//
//		$(document).click(function(){
//	        $('.lang-list').slideUp();
//	    });


		$('.close, .bg, .chat-close').click(function(e) {
				e.preventDefault();
				$('.dialog, .bg, #popup-chat, div.complainForm, #invite-form, #invite-form-refuse').hide();
				$('#popup-chat').removeAttr('id');
				//XXX Why we have to restart chat at every dialog close?
//				if( window.chat ){
//						clearTimeout(chat.activityTimer);
//						chat.lpRestart();
//				}
		});

		$(document).bind('keydown', function (event) {
			if (event.keyCode == 27) {
          event.preventDefault();
					$('.dialog, .bg, #popup-chat, div.complainForm, #invite-form').hide();
          $('#popup-chat').removeAttr('id');
          //XXX Why we have to restart chat at every dialog close?
//          if( window.chat ){
//							clearTimeout(chat.activityTimer);
//							chat.lpRestart();
//					}
			}
		});

		// Own Question
		$('#js-q').bind('change', function(e) {
			if($(this).val() == '0') {
				$('.chat-textfield').show();
			} else {
				$('.chat-textfield').hide();
			}
		});

		// Prevent invite type change by friend type select after manual invite type selection
		$('#invite-selectors input').bind('change', function(e) {
			user_clicked_type = true;
		});

		
		/* Exit button */
		$('#exit-link').click(function(){
			var
				$link = $(this),
				parOnClass = 'exit-confirm-on',
				$par = $(this).closest('div.username').addClass( parOnClass ),
				$confirm = $( '#exit-confirm' )
					.slideDown( 'fast', function(){
						
						})
			$('#exit-confirm-no')
				.unbind('click')
				.bind('click' , function(){
					$confirm.slideUp( 'fast', function(){
						$par.removeClass( parOnClass );
						});
					});
					
			$('#exit-confirm-yes')
				.unbind('click')
				.bind('click' , function(){
					$link.unbind('click').click(); 
					});
			return false;
			});
			
		/* User avatar balloon */
		(function(){
			var
				/** @type {jQuery} */
				$balloon,
				/** @type {jQuery} */
				$balloonContent,
				_settings = {
					offsetLeft : 16,
					offsetTop : - 16,
					hideDelay : 500,
					showDelay : 200,
					activeClass : 'user-balloon-active',
					dataIdField : '__userBalloonId'
					},
				inactivePos = {
					left : -9000,
					top : -9000
					},
				/** 
				 * Global counter of all targets
				 * @type {Number}
				 */
				globalNum = 0,
				/** @type {jQuery} */
				$target,
				activeTargetNum,
				/** 
				 * Data of active user
				 * @type {Object}
				 */
				user = {
					/** @type {Number} */
					id : undefined,
					/** @type {String} */
					name : undefined,
					/** @type {String} */
					profileTargetBlank : false
					},
				/** @type {Boolean} */
				isActive = false,
				/** @type {Number} */
				hideTimer,
				/** @type {Number} */
				showTimer;
				
			function fillBalloonForUser( u ){
				if ( ! $balloonContent || ! u || ! u.id ){
					return;
					}
				var
					html = [];
				html.push(
					'<ul id="user-balloon-links">',
						'<li>',
							'<a href="/users/view/' , u.id , '" id="user-balloon-link-chat">' ,
								LT.t('userBalloonChat'),
							'</a>',
						'<li>',
							'<a href="/users/view/' , u.id , '" id="user-balloon-link-profile"' ,
								u.profileTargetBlank
									? ' target="_blank"'
									: ''
								, '>',
								LT.t('userBalloonProfile'),
							'</a>',
//						'<li>',
//							'<a href="/users/view/' , u.id , '" id="user-balloon-link-exchange">',
//								FLRT.t( 'userBalloonExchange') ,
//							'</a>',
//						'</li>',
					'</ul>'
					)
				$balloonContent.html( html.join('') );
				}
			/** 
			 * @param {jQuery} target to place balloon near
			 */
			function placeBalloon( $target ){
				var
					offset = $target.offset(),
					tw = $target.outerWidth(),
					th = $target.outerHeight(),
					bw = $balloon.outerWidth(),
					bh = $balloon.outerHeight();
				$balloon.css( {
					left : offset.left + tw + _settings.offsetLeft,
					top : offset.top - bh + _settings.offsetTop
					} );
				}
			function hideBalloon(){
				if ( hideTimer ){
					clearTimeout( hideTimer );
					hideTimer = undefined;
					}
				isActive = false;
				hideTimer = setTimeout(function(){
					if ( ! isActive ){
						$balloon
							.removeClass( _settings.activeClass )
							.css( inactivePos );
						}
					}, _settings.hideDelay );
				}
				
			function onMouseOutOfTarget(){
				activeTargetNum = NaN;
				hideBalloon();
				}
				
			/** 
			 * @param {jQuery}
			 */
			function getTargetId( $t ){
				if ( ! $t || ! $t[0] ){
					return NaN;
					}
				var 
					tid = $.data($t[0] , _settings.dataIdField );
				if ( isNaN ( + tid ) ){
					$.data( $t[0] , _settings.dataIdField , tid = globalNum ++ );
					}
				return tid;
				}
			
			/** 
			 * @param {jQuery} Potential target
			 */
			function showBalloon( $t ){
				if ( showTimer ){
					clearTimeout( showTimer );
					showTimer = undefined;
					}
				showTimer = setTimeout(function(){
					if ( getTargetId( $t ) != activeTargetNum ){
						return;
						}
					$target = $t;
					if ( ! $balloon || ! $balloon.length ){
						/* Creating balloon at first time */
						$balloon = $( [
							'<div id="user-balloon">',
								'<div id="user-balloon-core">',
									'<div id="user-balloon-content" />',
								'</div>',
								'<span class="user-balloon-cloud" id="user-balloon-cloud-1"/>',
								'<span class="user-balloon-cloud" id="user-balloon-cloud-2" />',
							'</div>'].join('') )
							.hover(
								function(){
									isActive = true
									},
								hideBalloon)
							.delegate( '#user-balloon-link-chat' , 'click', function(){
								openChat( user.id );
								hideBalloon()
								return false;
								} )
							.appendTo(document.body);
						$balloonContent = $balloon.find( '#user-balloon-content' );
						}
					isActive = true;
					user.id = $target.searchInClass( 'user-avatar-id-' );
					user.profileTargetBlank = $target.searchInClass( 'user-avatar-profileTargetBlank-' );
					fillBalloonForUser( user );
					setTimeout(function(){
						$balloon.addClass( _settings.activeClass );
						}, 10)
					placeBalloon( $target );
					$target
						.unbind( 'mouseout' , hideBalloon )
						.bind( 'mouseout' , hideBalloon );
					}, _settings.showDelay);
				}
			$(document.body)
				.delegate( 'img.user-avatar' , 'mouseover' , function(){
					activeTargetNum = getTargetId( $( this ) );
					showBalloon( $( this ) );
					} )
				.delegate( 'img.user-avatar' , 'mouseout' , function(){
					activeTargetNum = NaN;
					} )
				
			})();

		if( FLRT.userToChat && FLRT.userToChat.id ){
			openChat( FLRT.userToChat.id );
			}

			
	/* Avatar upload on inner pages except profile */
	;(function(){
		function allowUpload( settings ){
			var
				_settings = {
					busy          : function(){},
					free          : function(){},
					complete      : function(){},
					error         : function(){},
					uploadUrl     : FLRT.photoUploadUrl || location.href,
					areaBusyClass : 'upload-busy',
					needHardConfirm : false	
					},
				$uploadBtn,
				scriptData = {
					PHPSESSID : FLRT.sessionId,
					ajax : 1
					},
				$upl,
				validExt = ['jpg', 'jpeg', 'gif', 'png'];
			if ( settings.button ){
				$uploadBtn = $( settings.button );
				delete settings.button;
				}

			settings && $.extend( _settings, settings );

			if ( _settings.needHardConfirm && window[ 'EmailConfirmLocker' ] ) {
				$uploadBtn.click(EmailConfirmLocker.confirm);
				return false;
			}
			
			if ( ! $uploadBtn.length ){
				return false;
				}
			/* No needed flash plugin, so will using regular single-file ajax uploading */
			new AjaxUpload( $uploadBtn, {
				action 		: _settings.uploadUrl,
				name 		: 'Photos',
				hoverClass 	: 'hover', 
				data		: {'ajax' : 1}, 
				onSubmit	: function(file, extension){
					if ( $.inArray(extension.toString().toLowerCase(), validExt ) < 0){
						FLRT.Confirm({
							text       : j( LT.text.galleryUploadPossibleFiles, ' ', validExt.join(', '), '.' ),
							yesCaption : 'Ok',
							noCaption  : null
						});
						return false;
						}
					busy();
					},
				onComplete 	: function( uploader, response ){
					onPhotoUploaded( response );
					free();
					}
				});
				
			/** 
			 * Handles 'one photo successfully uploaded' event
			 * @param {String} response
			 */
			function onPhotoUploaded( response ){
				var data;
				if ( 
					response 
					&& ( data = LT.Helpers.Text.text2json(response))
					&& data 
					&& data.picture){
					_settings.complete( data.picture );
					}
				else{
					_settings.error( response );
					}
				}	
			function busy(){
				$uploadBtn.addClass( 'n-button-adding_loading' );
				_settings.busy();
				}
			function free(){
				$uploadBtn.removeClass( 'n-button-adding_loading' );
				_settings.free();
				}
			}
		
			
		
		allowUpload({
			button : $( '#photo-upload' ),
			needHardConfirm : false,//! ( typeof window['needHardConfirm'] == 'undefine' || window['needHardConfirm'] == 0 ),
			complete : function(){
				/* 
				 * XXX Something strange is going on here man. 
				 * Seems like we cannot just update avatar on fly
				 * Because we cannot account for all conditions
				 * So here it is as simplest as sad answer: refresh page 
				 * after success uploading and let the server solves
				 * all problems
				 */
				SitePage.refresh();
				}
			});
			
		$( '.action-uploadAvatar' ).each(function(){
			allowUpload({
				button : this,
				needHardConfirm : false, //! ( typeof needHardConfirm == 'undefine' || needHardConfirm == 0 ),
				complete : function( picture ){
					SitePage.refresh();
					}
				});
			});
			
		})();

    $('.button-superstar').click(function() {
        FLRT.PaymentDialog.showSuperstar();
        return false;
    });

    $('.button-top').click(function() {
        FLRT.PaymentDialog.showTopfaces();
        return false;
    });
});
